<template>
  <div class="app-container">
    <div v-has-perm="['nljs_report_batch_statistics']" style="width: 100%">
      <div class="sel-batch"></div>
      <el-row :gutter="15">
        <el-col :span="12">
          <div class="cards">
            <div class="op-area">
              <div class="b-title">批次填报统计</div>
            </div>
            <div class="content">
              <div class="chart-item cards-bg-clor1">
                <div class="num">
                  <div class="title_a">
                    <img src="@/assets/images/fill.png" alt="" class="icon" />
                    <span class="title">已填报</span>
                  </div>
                  <span class="value">{{ statisticalData.submittedCompanyCount }}</span>
                </div>
                <div>
                  <el-progress
                    type="circle"
                    color="#4DC4C0"
                    :width="110"
                    :percentage="
                      parseFloat(
                        (
                          (statisticalData.submittedCompanyCount /
                            (statisticalData.submittedCompanyCount +
                              statisticalData.notSubmittedCompanyCount || 1)) *
                          100
                        ).toFixed(1)
                      )
                    "
                  >
                    <template #default="{ percentage }">
                      <span class="percentage-value">{{ percentage }}%</span>
                    </template>
                  </el-progress>
                </div>
              </div>
              <div class="chart-item cards-bg-clor2">
                <div class="num">
                  <div class="title_a">
                    <img src="@/assets/images/nofill.png" alt="" class="icon" />
                    <span class="title">未填报</span>
                  </div>
                  <span class="value">{{ statisticalData.notSubmittedCompanyCount }}</span>
                </div>
                <div>
                  <el-progress
                    type="circle"
                    color="#1777FF"
                    :width="110"
                    :percentage="
                      parseFloat(
                        (
                          (statisticalData.notSubmittedCompanyCount /
                            (statisticalData.submittedCompanyCount +
                              statisticalData.notSubmittedCompanyCount || 1)) *
                          100
                        ).toFixed(1)
                      )
                    "
                  >
                    <template #default="{ percentage }">
                      <span class="percentage-value">{{ percentage }}%</span>
                    </template>
                  </el-progress>
                </div>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="cards">
            <div class="op-area">
              <div class="b-title">审核状况统计</div>
              <!-- <el-select
                v-model="selBatch"
                placeholder="请选择批次"
                size="default"
                style="width: 240px"
                clearable
                @change="changeBatch"
              >
                <el-option
                  v-for="item in batchList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select> -->
            </div>
            <div class="content">
              <div class="chart-item2 cards-bg-clor3">
                <div class="num">
                  <div class="title_a">
                    <img src="@/assets/images/fill.png" alt="" class="icon" />
                    <span class="title">通过</span>
                  </div>
                  <span class="value">{{ statisticalData.approvedCount }}</span>
                </div>
                <div class="prog">
                  <el-progress
                    type="circle"
                    color="#4DC4C0"
                    :width="90"
                    :percentage="
                      parseFloat(
                        (
                          (statisticalData.approvedCount /
                            (statisticalData.approvedCount +
                              statisticalData.rejectedCount +
                              statisticalData.pendingCount || 1)) *
                          100
                        ).toFixed(1)
                      )
                    "
                  >
                    <template #default="{ percentage }">
                      <span class="percentage-value">{{ percentage }}%</span>
                    </template>
                  </el-progress>
                </div>
              </div>
              <div class="chart-item2 cards-bg-clor4">
                <div class="num">
                  <div class="title_a">
                    <img src="@/assets/images/reject.png" alt="" class="icon" />
                    <span class="title">不通过</span>
                  </div>
                  <span class="value">{{ statisticalData.rejectedCount }}</span>
                </div>
                <div class="prog">
                  <el-progress
                    type="circle"
                    color="#F76560"
                    :width="90"
                    :percentage="
                      parseFloat(
                        (
                          (statisticalData.rejectedCount /
                            (statisticalData.approvedCount +
                              statisticalData.rejectedCount +
                              statisticalData.pendingCount || 1)) *
                          100
                        ).toFixed(1)
                      )
                    "
                  >
                    <template #default="{ percentage }">
                      <span class="percentage-value">{{ percentage }}%</span>
                    </template>
                  </el-progress>
                </div>
              </div>
              <div class="chart-item2 cards-bg-clor5">
                <div class="num">
                  <div class="title_a">
                    <img src="@/assets/images/nofill.png" alt="" class="icon" />
                    <span class="title">待审核</span>
                  </div>
                  <span class="value">{{ statisticalData.pendingCount }}</span>
                </div>
                <div class="prog">
                  <el-progress
                    type="circle"
                    color="#1777FF"
                    :width="90"
                    :percentage="
                      parseFloat(
                        (
                          (statisticalData.pendingCount /
                            (statisticalData.approvedCount +
                              statisticalData.rejectedCount +
                              statisticalData.pendingCount || 1)) *
                          100
                        ).toFixed(1)
                      )
                    "
                  >
                    <template #default="{ percentage }">
                      <span class="percentage-value">{{ percentage }}%</span>
                    </template>
                  </el-progress>
                </div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <div class="app-content">
      <div class="title-area">
        <div class="first">
          <img src="@/assets/images/batch-list.png" alt="" />
          <span class="f-title">批次列表</span>
        </div>
        <div>
          <el-button
            v-has-perm="['nljs_report_batch_add']"
            type="primary"
            plain
            :icon="Plus"
            @click="addPatch"
          >
            新增批次
          </el-button>
          <el-button
            v-has-perm="['nljs_report_batch_del']"
            type="danger"
            :disabled="!batchIds.length"
            plain
            :icon="Delete"
            @click="delBatchs"
          >
            批量删除
          </el-button>
          <el-button
            v-has-perm="['nljs_report_batch_view']"
            icon="refresh"
            type="primary"
            plain
            @click="handleQuery()"
          >
            刷新
          </el-button>
        </div>
      </div>
      <el-table
        v-has-perm="['nljs_report_batch_view']"
        v-loading="loading"
        class="table-list"
        :data="tableDataAdmin"
        header-row-class-name="admin"
        highlight-current-row
        border
        height="calc(100vh - 500px)"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          v-has-perm="['nljs_report_batch_del', 'nljs_report_batch_add']"
          type="selection"
          width="55"
          align="center"
        />
        <el-table-column prop="id" label="批次ID" width="90"></el-table-column>
        <el-table-column prop="batchName" label="批次名称" min-width="150"></el-table-column>
        <el-table-column prop="batchDescription" label="批次描述" min-width="150"></el-table-column>
        <el-table-column prop="endTime" label="截止日期" width="180"></el-table-column>
        <el-table-column prop="warningThreshold" label="告警阈值" width="100" center>
          <template #default="scope">
            <span style="color: #ea3f39">{{ scope.row.warningThreshold }}%</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" width="100" label="批次状态">
          <!-- 0-关闭 1-开启 -->
          <template #default="scope">
            <!-- 超过截止时间 -->
            <template v-if="new Date(scope.row.endTime).getTime() < new Date().getTime()">
              <el-switch
                :model-value="0"
                size="small"
                :active-value="1"
                :inactive-value="0"
                @change="changeSwitchStatus(scope.row)"
              />
            </template>
            <template v-else>
              <el-switch
                v-model="scope.row.status"
                size="small"
                :disabled="statusLoading"
                :active-value="1"
                :inactive-value="0"
                @change="changeSwitchStatus(scope.row)"
              />
            </template>
            <!-- <el-tag :type="statusTag[scope.row.status]">{{ statusMap[scope.row.status] }}</el-tag> -->
          </template>
        </el-table-column>
        <el-table-column prop="publishStatus" width="100" label="发布状态">
          <!-- 0-未发布 1-已发布 -->
          <template #default="scope">
            <el-tag :type="publishStatusTag[scope.row.publishStatus]">
              {{ publishStatusMap[scope.row.publishStatus] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createBy" label="创建人" width="110"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-if="scope.row.publishStatus == 0"
              v-has-perm="['nljs_report_batch_publish']"
              link
              type="primary"
              :icon="Document"
              size="small"
              @click="openPushDialog(scope.row)"
            >
              发布
            </el-button>
            <el-button
              v-if="scope.row.publishStatus == 1"
              v-has-perm="['nljs_report_record_view']"
              link
              type="primary"
              :icon="Document"
              size="small"
              @click="goBatchList(scope.row)"
            >
              查看
            </el-button>
            <el-button
              v-if="scope.row.publishStatus == 0"
              v-has-perm="['nljs_report_batch_edit']"
              link
              type="success"
              :icon="Edit"
              size="small"
              @click="editBatch(scope.row)"
            >
              修改
            </el-button>
            <el-button
              lv-has-perm="['nljs_report_batch_del']"
              link
              type="danger"
              :icon="Delete"
              size="small"
              @click="delBatch(scope.row)"
            >
              删除
            </el-button>
            <!-- <el-tag v-if="scope.$index === 0" type="danger" style="margin-left: 10px">
              逾期已自动审核
            </el-tag> -->
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div v-if="queryParams.total > 0" class="pager-container">
        <pagination
          v-model:total="queryParams.total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="handlePagination"
        />
      </div>
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="batchTitle"
      width="55%"
      top="5vh"
      :close-on-click-modal="false"
      @close="reset"
    >
      <div class="year">
        <el-steps style="width: 100%" :active="actives" finish-status="success" align-center>
          <el-step title="选择指标分类" />
          <el-step title="填写批次信息" />
        </el-steps>
        <div class="btn">
          <el-button @click="next">下一步</el-button>
        </div>
        <el-form
          ref="batchFormRef"
          :model="batchForm"
          :rules="batchFormRules"
          label-width="auto"
          class="batch-form"
        >
          <el-row :gutter="20">
            <el-col :span="10" class="tree-content">
              <el-tree
                ref="catTreeRef"
                class="mt-2 cat-tree"
                :data="categoryList"
                :props="{ children: 'children', label: 'name' }"
                :expand-on-click-node="false"
                :filter-node-method="handleFilter"
                default-expand-all
                highlight-current
                @node-click="handleNodeClick"
              />
            </el-col>
            <el-col v-show="showForm" :span="14">
              <el-form-item label="选择指标" prop="indicatorId">
                <el-select
                  v-model="batchForm.indicatorId"
                  placeholder="请选择指标"
                  size="default"
                  style="width: 100%"
                  clearable
                  filterable
                  @change="changeIndicator"
                >
                  <el-option
                    v-for="item in indicatorList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="所含表单" prop="formTags">
                <el-input v-model="batchForm.formTags" disabled></el-input>
              </el-form-item>
              <el-form-item label="计算周期" prop="calculationCycle">
                <el-select
                  v-model="batchForm.calculationCycle"
                  placeholder="请选择周期类型"
                  size="default"
                  style="width: 100%"
                  clearable
                  disabled
                  @change="changePeriodType"
                >
                  <el-option
                    v-for="item in periodOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="收集周期" prop="collectionPeriod">
                <template v-if="batchForm.calculationCycle == 'quarter'">
                  <el-quarter-picker
                    ref="quarterPickerRef"
                    v-model="batchForm.collectionPeriod"
                  ></el-quarter-picker>
                </template>
                <template v-else>
                  <el-date-picker
                    v-model="batchForm.collectionPeriod"
                    :type="periodTypeMap[calculationCycle]"
                    :format="periodFormat[calculationCycle]"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                    :placeholder="periodMap[calculationCycle]"
                  />
                </template>
              </el-form-item>
              <!-- <el-form-item label="选择类型" prop="formIds">
                <el-cascader v-model="batchForm.formIds" style="width: 100%" :options="typeOptions" :props="typeProps"
                  collapse-tags :collapse-tags-tooltip="true" clearable @change="changeType" />
              </el-form-item> -->
              <el-form-item label="批次名称" prop="batchName">
                <el-input v-model="batchForm.batchName" />
              </el-form-item>
              <el-form-item label="批次描述" prop="batchDescription">
                <el-input
                  v-model="batchForm.batchDescription"
                  type="textarea"
                  maxlength="500"
                  :rows="2"
                />
              </el-form-item>
              <!-- <el-form-item label="备注">
                <el-input v-model="batchForm.remark" type="textarea" :rows="2" />
              </el-form-item> -->
              <el-form-item label="截止日期" prop="endTime">
                <el-date-picker
                  v-model="batchForm.endTime"
                  type="datetime"
                  placeholder="请选择"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 100%"
                />
              </el-form-item>
              <el-form-item label="数据告警阈值" prop="warningThreshold">
                <el-input-number v-model="batchForm.warningThreshold" :min="0" :max="100" />
                <span class="threshold">%</span>
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-radio-group v-model="batchForm.status">
                  <el-radio label="禁用" :value="0"></el-radio>
                  <el-radio label="启用" :value="1"></el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="上传附件" prop="fileList">
                <manual-upload
                  ref="manualUploadRef"
                  v-model="batchForm.attachmentIds"
                  :accept="accept.join(',')"
                  :auto-upload="false"
                  show-file-list
                  :limit="3"
                >
                  <template #default>
                    <el-icon class="uploader-icon">
                      <Plus />
                    </el-icon>
                  </template>
                  <template #tip>
                    <div class="el-upload__tip">注：单个上传文件不超过10M</div>
                  </template>
                  <template #file="{ file, remove }">
                    <div class="file-card">
                      <span class="file-name" :title="file.name">{{ file.name }}</span>
                      <el-icon class="icon-remove" @click="handleRemove(file)">
                        <Close />
                      </el-icon>
                    </div>
                  </template>
                </manual-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="reset">取消</el-button>
          <el-button size="small" type="primary" @click="confirm">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="pushDialog" title="发布批次" width="700" :close-on-click-modal="false">
      <el-form
        ref="pushFormRef"
        class="push-form"
        :model="pushForm"
        :rules="pushRules"
        label-width="80px"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="发电类型" prop="powerUnits">
              <el-cascader
                v-model="pushForm.powerUnits"
                class="units"
                :options="powerOptions"
                :props="props"
                clearable
                filterable
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="3"
                :value-on-clear="() => null"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="区域" prop="areaUnits">
              <el-cascader
                v-model="pushForm.areaUnits"
                class="units"
                :options="areaOptions"
                :props="props"
                clearable
                filterable
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="3"
                :value-on-clear="() => null"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="选择单位" prop="unitIds">
              <select-tree
                ref="selectTreeRef"
                v-model="pushForm.unitIds"
                :props="{
                  children: 'children',
                  value: 'id',
                  label: 'name',
                }"
                multiple
                width="100%"
                :max-collapse-tags="3"
                :expand-on-click-node="false"
                :collapse-tags-tooltip="true"
                :collapse-tags="true"
                :check-strictly="true"
                :data="unitOptions"
                show-checkbox
              ></select-tree>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPuish">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="noticeVisible" title="填报须知" width="500" :close-on-click-modal="false">
      <div class="notice">
        {{ noticeStr }}
      </div>
      <div class="agree-check">
        <el-checkbox v-model="isAgree" label="我已阅读并同意以上填报须知" size="large" />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" type="primary" :disabled="!isAgree" @click="agree">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: 'Manage',
  inheritAttrs: false,
});

import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules, UploadProps } from 'element-plus';
import ElQuarterPicker from '@/components/Quarter/index.vue';
import { Document, Delete, Edit } from '@element-plus/icons-vue';
import BatchAPI from '@/api/batch/batch.api';
import FormAPI from '@/api/batch/form.api';
import UnitAPI from '@/api/system/unit.api';
import FileAPI from '@/api/system/file.api';
import DeptAPI from '@/api/system/dept.api';
import IndicatorAPI from '@/api/batch/indicator.api';
import SelectTree from '@/components/SelectTree/index.vue';
import { accept } from '@/utils/validate';
import ManualUpload from '@/components/Upload/ManualUpload.vue';
interface Tree {
  [key: string]: any;
}
const router = useRouter(); // 路由跳转
const selectTreeRef = ref();
const publishStatusTag = reactive<any>({
  0: 'danger',
  1: 'success',
});

const publishStatusMap = reactive<any>({
  0: '未发布',
  1: '已发布',
});
const batchTitle = ref('新增批次');
const dialogVisible = ref(false);
const actives = ref(0);
const showForm = ref(false);
const isAgree = ref(false);

const queryParams = reactive<{
  total: number;
  pageNum: number;
  pageSize: number;
  [key: string]: any;
}>({
  total: 0,
  pageNum: 1,
  pageSize: 10,
});

const selBatch = ref('');
const batchList = ref<any[]>([]);
const statisticalData = ref<{
  submittedCompanyCount?: number; // 已填报
  notSubmittedCompanyCount?: number; // 未填报
  approvedCount?: number; // 通过
  pendingCount?: number; // 待审核
  rejectedCount?: number; // 不通过
}>({
  submittedCompanyCount: 0, // 已填报
  notSubmittedCompanyCount: 0, // 未填报
  approvedCount: 0, // 通过
  pendingCount: 0, // 待审核
  rejectedCount: 0, // 不通过
});

const batchFormRef = ref<FormInstance>();
const pushFormRef = ref<FormInstance>();
const quarterPickerRef = ref<any>();
const calculationCycle = computed(() => {
  return batchForm.calculationCycle || 'month';
});
const batchForm = reactive<any>({
  id: '',
  indicatorId: '',
  formTags: '',
  formIds: [],
  calculationCycle: '',
  collectionPeriod: '',
  batchName: '',
  batchDescription: '',
  remark: '',
  endTime: '',
  warningThreshold: 0,
  attachmentIds: '',
  status: 1,
});
const categoryList = ref<any[]>([]);
const catTreeRef = ref();
const indicatorList = ref<any[]>([]);
const indicatorListMap = ref<any[]>([]);
const formListMap = ref<any>({});
const batchFormRules: FormRules = {
  indicatorId: [{ required: true, message: '请选择指标', trigger: 'change' }],
  // calculationCycle: [{ required: true, message: '请选择周期类型', trigger: 'change' }],
  collectionPeriod: [{ required: true, message: '请选择统计时间', trigger: 'change' }],
  batchName: [
    { required: true, message: '请输入批次名称', trigger: 'blur' },
    { min: 1, max: 500, message: '长度在 1 到 500', trigger: 'blur' },
  ],
  batchDescription: [{ required: true, message: '请输入批次描述', trigger: 'blur' }],
  endTime: [{ required: true, message: '请选择日期', trigger: 'change' }],
};

const periodOptions = reactive<{ label: string; value: string }[]>([
  { label: '月度', value: 'month' },
  { label: '季度', value: 'quarter' },
  { label: '年度', value: 'year' },
  { label: '半年度', value: 'halfyear' },
  { label: '周', value: 'week' },
  { label: '自定义', value: 'custom' },
]);
const periodMap: any = {
  month: '请选择月度',
  quarter: '请选择季度',
  year: '请选择年度',
  halfyear: '请选择半年度',
  week: '请选择周',
  custom: '请选择日期范围',
};
const periodTypeMap: any = {
  month: 'month',
  quarter: 'quarter',
  year: 'year',
  halfyear: 'halfyear',
  week: 'week',
  custom: 'daterange',
};
const periodFormat: any = {
  month: 'YYYY-MM',
  quarter: 'YYYY-QQ',
  year: 'YYYY',
  halfyear: 'YYYY-HH',
  week: 'YYYY-ww',
  custom: 'YYYY-MM-DD',
};
const changePeriodType = (val: string) => {
  console.log('val', val);
  batchForm.collectionPeriod = '';
};
// 级联选择器配置
const typeProps = { multiple: true };
const typeOptions = reactive<any>([]);

async function initTypeOptions() {
  const category: any = await FormAPI.getFormCategoryList();
  const formDefine: any = await FormAPI.getDefinitionAllList();
  const formDefineList: any[] = [];
  formDefine.map((item: any) => {
    if (item.status == 1) {
      formDefineList.push(item);
    }
  });
  category.forEach((item: any) => {
    const option: any = {};
    option['label'] = item.categoryName;
    option['value'] = item.id;
    option['children'] = formDefineList
      .filter((el: any) => el.categoryId == item.id)
      .map((v: any) => {
        return {
          label: v.formName,
          value: v.id,
        };
      });
    typeOptions.push(option);
  });
}

// const typeMap = reactive({
//   1: '新能源',
//   6: '火力',
//   9: '地方国网',
// });

const noticeStr = ref('xxx');
const noticeVisible = ref(false);

const loading = ref(false);
const batchIds = ref<number[] | string[]>([]);
// 表格等响应式数据用ref声明
const tableDataAdmin = ref<any>([]);

const pushDialog = ref<any>(false);
const pushForm = reactive<any>({
  id: undefined,
  powerUnits: [],
  areaUnits: [],
  unitIds: [],
});
const pushRules: FormRules = {
  unitIds: [{ required: false, message: '请选择发布单位', trigger: 'blur' }],
};
const powerTypeOptions = reactive<any[]>([
  { label: '储能', value: '储能' },
  { label: '风电', value: '风电' },
  { label: '光伏', value: '光伏' },
  { label: '燃煤', value: '燃煤' },
  { label: '燃气', value: '燃气' },
  { label: '热电联产', value: '热电联产' },
  { label: '生物质', value: '生物质' },
  { label: '水电', value: '水电' },
]);
const statusLoading = ref(false);
const props = {
  multiple: true,
  checkStrictly: false, // true-父子节点取消选中关联
};
const powerUnitOptions = ref<any[]>([]);
const areaUnitOptions = ref<any[]>([]);
const unitOptions = ref<any>([]);
const areaMap = ref<any>({});
const treeSelectRef = ref<any>(null);
const powerOptions = ref<any>([]);
const areaOptions = ref<any>([]);
const fileList = ref<any[]>([]);

const curRow = ref<any>({});

const changeBatch = () => {
  getStatisticsData();
};
const handleSelectionChange = (val: any) => {
  batchIds.value = val.map((item: any) => item.id);
  getStatisticsData();
};
const addPatch = () => {
  batchTitle.value = '新增批次';
  dialogVisible.value = true;
};
const delBatchs = () => {
  ElMessageBox.confirm('确认删除?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      BatchAPI.batchDel(batchIds.value).then(() => {
        ElMessage.success('批量删除成功!');
        handleQuery();
      });
    })
    .catch(() => {});
};
const goBatchList = (row: any) => {
  router.push({
    path: '/batch/list',
    query: {
      batchId: row.id,
    },
  });
};
const editBatch = (row: any) => {
  batchTitle.value = '修改批次';
  dialogVisible.value = true;
  showForm.value = true;
  BatchAPI.getBatchDetail(row.id).then((data: any) => {
    // batchForm.formIds = data.formList.map((item: any) => {
    //   return [item.categoryId, item.formId];
    // });
    batchForm.id = data.id;
    batchForm.indicatorId = data.indicatorId;
    batchForm.batchName = data.batchName;
    batchForm.batchDescription = data.batchDescription;
    batchForm.endTime = data.endTime;
    batchForm.warningThreshold = data.warningThreshold;
    batchForm.status = data.status;
    batchForm.calculationCycle = data.indicator?.calculationCycle;
    batchForm.collectionPeriod = data.collectionPeriod;
    batchForm.attachmentIds = data.attachmentIds;
    const {
      commonForms = [],
      coalForms = [],
      waterElectricityForms = [],
      photovoltaicForms = [],
      biomassForms = [],
      windPowerForms = [],
      gasForms = [],
      energyStorageForms = [],
      cogenerationForms = [],
    } = data;
    const nameArr = commonForms
      .concat(
        coalForms,
        waterElectricityForms,
        photovoltaicForms,
        biomassForms,
        windPowerForms,
        gasForms,
        energyStorageForms,
        cogenerationForms
      )
      .map((item: any) => {
        return item.formName;
      });
    const names = [...new Set(nameArr)].join(', ');
    console.log('names', names);
    batchForm.formTags = names;
  });
};
const delBatch = (row: any) => {
  ElMessageBox.confirm('确认删除?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      BatchAPI.delBatch(row.id).then(() => {
        ElMessage.success('删除成功!');
        handleQuery();
      });
    })
    .catch(() => {});
};
const reset = () => {
  dialogVisible.value = false;
  actives.value = 0;
  showForm.value = false;
  batchFormRef.value?.resetFields();
  batchForm.id = '';
  batchForm.batchName = '';
  batchForm.batchDescription = '';
  batchForm.endTime = '';
  batchForm.warningThreshold = 0;
  batchForm.status = 1;
  fileList.value = [];
};
const manualUploadRef = ref<InstanceType<typeof ManualUpload>>();
const confirm = () => {
  batchFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (!batchForm.indicatorId) {
        ElMessage.error('请选择指标!');
        return;
      }
      // const arr = batchForm.formIds.map((item: any) => {
      //   return item[1];
      // });
      await manualUploadRef.value?.uploadFilesHttp();
      const params = {
        reportBatch: {
          id: undefined,
          indicatorId: batchForm.indicatorId,
          collectionPeriod: batchForm.collectionPeriod,
          batchName: batchForm.batchName,
          attachmentIds: batchForm.attachmentIds,
          batchDescription: batchForm.batchDescription,
          endTime: batchForm.endTime,
          warningThreshold: batchForm.warningThreshold,
          status: 1,
        },
      };
      if (batchForm.id) {
        params.reportBatch.id = batchForm.id;
        BatchAPI.editBatch(params).then(() => {
          ElMessage.success('修改成功!');
          reset();
          handleQuery();
        });
      } else {
        BatchAPI.addBacth(params).then(() => {
          ElMessage.success('新增成功!');
          reset();
          queryParams.pageNum = 1;
          handleQuery();
        });
      }
    }
  });
};

const handlePagination = () => {
  // initTypeOptions();
  handleQuery();
};
// 查询批次列表
const handleQuery = () => {
  loading.value = true;
  const params = {
    current: queryParams.pageNum,
    size: queryParams.pageSize,
    reportBatch: {},
  };
  BatchAPI.getBatchList(params)
    .then((data: any) => {
      // delFlag-0:正常;1:(软)删除
      tableDataAdmin.value = data.records.filter((item: any) => item.delFlag == '0');
      const arr = data.records.filter((item: any) => item.publishStatus == 1);
      batchList.value = arr.map((item: any) => {
        return {
          label: item.batchName,
          value: item.id,
        };
      });
      queryParams.total = data.total;
      loading.value = false;
    })
    .catch((err) => {
      console.log('err-', err);
      loading.value = false;
    });
};

const getStatisticsData = () => {
  BatchAPI.getStatistics({ batchIds: batchIds.value.join(',') }).then((data: any) => {
    statisticalData.value = {
      submittedCompanyCount: data.submittedCompanyCount || 0,
      notSubmittedCompanyCount: data.notSubmittedCompanyCount || 0,
      approvedCount: data.approvedCount || 0,
      pendingCount: data.pendingCount || 0,
      rejectedCount: data.rejectedCount || 0,
    };
  });
};
// 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
const editBatchAttach = (type: number) => {
  if (!batchForm.id) {
    return;
  }
  const params: any = {
    reportBatch: {
      id: batchForm.id,
      attachmentIds: batchForm.attachmentIds,
    },
  };
  BatchAPI.editBatch(params).then(() => {
    ElMessage.success(type === 1 ? '上传附件成功！' : '删除附件成功！');
  });
};
const handleRemove = async (file: any) => {
  await manualUploadRef.value?.remove(file);
  editBatchAttach(2);
};

const agree = () => {
  router.push({
    path: '/batch/fill',
    query: {
      no: curRow.value.no,
      status: curRow.value.status,
      checkStatus: curRow.value.checkStatus,
      typeList: JSON.stringify(curRow.value.typeList),
    },
  });
};

function changeSwitchStatus(row: any) {
  const params = {
    id: parseInt(row.id),
    status: row.status,
  };
  ElMessageBox.confirm('确认修改?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .catch(
      () =>
        new Promise(() => {
          row.status = row.status == 0 ? 1 : 0;
        })
    )
    .then((_) => {
      statusLoading.value = true;
      return BatchAPI.editBatch({
        reportBatch: params,
      });
    })
    .then(() => ElMessage.success('修改成功'))
    .catch(() => {
      ElMessage.error('修改失败');
      row.status = row.status == 0 ? 1 : 0;
    })
    .finally(() => {
      statusLoading.value = false;
    });
}
function openPushDialog(row: any) {
  pushDialog.value = true;
  pushForm.id = row.id;
}
function submitPuish() {
  console.log('push-', pushForm);
  const idsArr: string[] = [];
  pushForm.powerUnits &&
    pushForm.powerUnits.forEach((item: string[]) => {
      idsArr.push(item[1]);
    });
  pushForm.areaUnits &&
    pushForm.areaUnits.forEach((item: string[]) => {
      idsArr.push(item[1]);
    });
  const unitIdsArr = [...new Set(idsArr.concat(pushForm.unitIds))].map((item) => Number(item));
  console.log('unitIdsArr-', unitIdsArr);
  BatchAPI.pushBatch(toRaw(unitIdsArr), pushForm.id).then(() => {
    ElMessage.success('发布成功!');
    pushFormRef.value?.resetFields();
    pushDialog.value = false;
    handleQuery();
  });
}

async function initUnitList() {
  UnitAPI.getTree().then((data: any) => {
    unitOptions.value = data;
  });
}

const changePower = (val: any) => {
  if (!val) {
    return;
  }
  getUnitList(1, { energyType: val });
};
const changeArea = (val: any) => {
  if (!val) {
    return;
  }
  getUnitList(2, { areaId: val });
};
const getUnitList = (type: number = 0, params?: any) => {
  UnitAPI.getAllList(params)
    .then((data: any) => {
      if (type == 0) {
        powerUnitOptions.value = data.map((item: any) => {
          return {
            label: item.name,
            value: item.id,
          };
        });
        areaUnitOptions.value = data.map((item: any) => {
          return {
            label: item.name,
            value: item.id,
          };
        });
      } else {
        if (type == 1) {
          powerUnitOptions.value = data.map((item: any) => {
            return {
              label: item.name,
              value: item.id,
            };
          });
        } else {
          areaUnitOptions.value = data.map((item: any) => {
            return {
              label: item.name,
              value: item.id,
            };
          });
        }
      }
    })
    .catch((err) => {
      console.error(err);
    });
};

const initFormList = () => {
  FormAPI.getDefinitionAllList().then((data: any) => {
    data.forEach((item: any) => {
      formListMap.value[item.id] = item.formName;
    });
  });
};

const next = () => {
  if (actives.value++ > 1) {
    actives.value = 0;
  }
  if (actives.value == 1) {
    showForm.value = true;
  }
};
const handleFilter = (value: string, data: Tree) => {
  if (!value) return true;
  return data.label.includes(value);
};
const handleNodeClick = (data: { [key: string]: any }) => {
  showForm.value = true;
  getIndicatorByCatId({ categoryId: data.id });
};
// 初始化指标树形结构
const initIndicatorTree = () => {
  IndicatorAPI.getIndicatorCategoryTree()
    .then((data: any) => {
      categoryList.value = data;
    })
    .catch((err) => {});
  getIndicatorByCatId();
};
const getIndicatorByCatId = (params?: any) => {
  IndicatorAPI.getIndicatorAllList(params ?? undefined)
    .then((data: any) => {
      indicatorList.value = data.map((item: any) => {
        return {
          label: item.name,
          value: item.id,
          categoryId: item.categoryId,
        };
      });
      indicatorListMap.value = data;
    })
    .catch((err) => {});
};
const changeIndicator = (val: any) => {
  if (!val) {
    batchForm.formTags = '';
    batchForm.calculationCycle = '';
    return;
  }
  const obj = indicatorListMap.value.find((item: any) => item.id == val);
  console.log('obj-', obj);
  batchForm.calculationCycle = obj.calculationCycle;
  /*
    commonFormIds	关联通用表单ID列表(多个ID用逗号分隔,如:1,2,3)
    coalFormIds	关联燃煤表单ID列表(多个ID用逗号分隔,如:1,2,3)	
    waterElectricityFormIds	关联水电表单ID列表(多个ID用逗号分隔,如:1,2,3)
    photovoltaicFormIds	关联光伏表单ID列表(多个ID用逗号分隔,如:1,2,3)
    biomassFormIds	关联生物质表单ID列表(多个ID用逗号分隔,如:1,2,3)
    windPowerFormIds	关联风电表单ID列表(多个ID用逗号分隔,如:1,2,3)
    gasFormIds	关联燃气表单ID列表(多个ID用逗号分隔,如:1,2,3)
    energyStorageFormIds	关联储能表单ID列表(多个ID用逗号分隔,如:1,2,3)	
    cogenerationFormIds	关联热电联产表单ID列表(多个ID用逗号分隔,如:1,2,3)
  */
  const {
    commonFormIds = '',
    coalFormIds = '',
    waterElectricityFormIds = '',
    photovoltaicFormIds = '',
    biomassFormIds = '',
    windPowerFormIds = '',
    gasFormIds = '',
    energyStorageFormIds = '',
    cogenerationFormIds = '',
  } = obj;
  const alls =
    commonFormIds +
    ',' +
    coalFormIds +
    ',' +
    waterElectricityFormIds +
    ',' +
    photovoltaicFormIds +
    ',' +
    biomassFormIds +
    ',' +
    windPowerFormIds +
    ',' +
    gasFormIds +
    ',' +
    energyStorageFormIds +
    ',' +
    cogenerationFormIds;
  const idsArr = alls.split(',').filter((item) => item && item !== 'null' && item !== 'undefined');
  console.log('idsArr-', idsArr);
  const ids = [...new Set(idsArr)];
  console.log('ids-', ids);
  ids.forEach((item: any) => {
    batchForm.formTags += formListMap.value[item] + ', ';
  });
};
// 获取 发电类型 区域 单位列表
const handleAllUnits = async () => {
  const areaList = await DeptAPI.getListAll();
  areaList.forEach((item: any) => {
    areaMap.value[item.id] = item.name;
  });

  await UnitAPI.getAllList().then((data: any) => {
    const powerList: any = [];
    data.forEach((item: any) => {
      if (item.energyType) {
        powerList.push(item.energyType);
      }
    });
    const unitList = data.map((item: any) => item.areaId);
    const powerSet = [...new Set(powerList)];
    const areaSet = [...new Set(unitList)];
    const powerArr: any = [];
    const areaArr: any = [];
    powerSet.forEach((item: any) => {
      powerArr.push({
        label: item,
        value: item,
        children: data
          .filter((el: any) => el.energyType == item)
          .map((v: any) => {
            return {
              label: v.name,
              value: v.id,
            };
          }),
      });
    });
    areaSet.forEach((item: any) => {
      areaArr.push({
        label: areaMap.value[item],
        value: item,
        children: data
          .filter((el: any) => el.areaId == item)
          .map((v: any) => {
            return {
              label: v.name,
              value: v.id,
            };
          }),
      });
    });
    powerOptions.value = powerArr;
    areaOptions.value = areaArr;
  });
};

onMounted(async () => {
  getStatisticsData(); // 获取统计数据
  handleQuery(); // 查询批次列表
  initFormList(); // 获取表单定义列表map
  initIndicatorTree(); // 指标树形结构
  initUnitList(); // 发布-获取全量单位列表
  handleAllUnits(); // 发布-获取 发电类型 区域 单位数据
});

// 组件卸载之前执行的函数
onBeforeUnmount(() => {});
</script>

<style lang="scss" scoped>
.title-area {
  display: flex;
  justify-content: space-between;
  align-items: center;

  img {
    width: 18px;
    height: 18px;
  }

  .first {
    display: flex;
    align-items: center;
  }

  .f-title {
    font-family: PingFang SC, PingFang SC;
    font-weight: 600;
    font-size: 16px;
    color: #1d2129;
    padding-left: 5px;
  }
}

.table-list {
  width: 100%;
  margin-top: 10px;
}

:deep(.admin th) {
  background-color: #f7f8fa !important;
}

:deep(.admin) {
  color: #494a4b;
}

.sel-batch {
  display: flex;
  justify-content: flex-end;
  padding: 0 0 10px;
}

.cards {
  height: 227px;
  overflow: hidden;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  /* x轴偏移量 y轴偏移量 模糊 扩张 颜色(透明度) */
  box-shadow: 0px 0px 12px 0px rgba(0, 0, 0, 0.12);
  background-color: #ffffff;
}

.op-area {
  display: flex;
  justify-content: space-between;
}

.b-title {
  font-family: PingFang SC, PingFang SC;
  font-weight: 600;
  font-size: 16px;
  color: #1d2129;
  font-style: normal;
  text-transform: none;
}

.content {
  display: flex;
  justify-content: space-between;
  // height: 154px;
  height: calc(100% - 48px);
  margin-top: 16px;
}

.percentage-value {
  display: block;
  font-family: DIN, DIN;
  font-weight: 500;
  font-size: 16px;
  // color: #1d2129;
}

.chart-item {
  display: flex;
  // background: linear-gradient(#f2f9fc 100%, #f8fffe 100%);
  padding: 15px;
  width: 48%;
  justify-content: space-between;
  border-radius: 5px;
}

.chart-item2 {
  display: flex;
  // background: linear-gradient(#f2f9fc 100%, #f8fffe 100%);
  padding: 15px;
  width: 32%;
  justify-content: space-between;
  border-radius: 5px;

  .prog {
    display: flex;
    align-items: center;
  }
}

.cards-bg-clor1 {
  background: linear-gradient(228deg, #f2f9fc 0%, #f8fffe 100%);
  // background: #94e2d8;
}

.cards-bg-clor2 {
  background: linear-gradient(228deg, #f1f5ff 0%, #f8faff 100%);
  // background: #9db7f7;
}

.cards-bg-clor3 {
  background: rgba(22, 166, 161, 0.04);
  // background: #94e2d8;
}

.cards-bg-clor4 {
  background: rgba(247, 101, 96, 0.04);
}

.cards-bg-clor5 {
  background: rgba(23, 119, 255, 0.04);
  // background: #9db7f7;
}

.num {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 6px 0;
}

.title_a {
  display: flex;
  align-items: center;
}

.title {
  font-size: 13px;
  color: #595757;
  padding-left: 5px;
}

.value {
  font-weight: 600;
  font-size: 26px;
}

.icon {
  width: 18px;
  height: 18px;
}

/* dialog */
.year {
  padding: 10px 15px;

  .tree-content {
    max-height: 100%;
    overflow-y: auto;
  }

  .cat-tree {
    height: 95%;
  }
}

.btn {
  display: flex;
  justify-content: flex-end;
}

.batch-form {
  margin-top: 10px;
}

.threshold {
  margin-left: 5px;
}

.upload-demo {
  width: 100%;

  :deep(.el-upload--text) {
    width: 100%;
  }
}

.uploader-icon {
  background: #f7f8fa;
  border-radius: 4px;
  border: 1px dashed #c9cdd4;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}

.uploader-icon:hover {
  border-color: #409eff;
  background: #eff2f8;
}

.file-card {
  line-height: 16px;
  padding: 10px;
  padding-right: 20px;
  box-sizing: border-box;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  /* x轴偏移量 y轴偏移量 模糊 扩张 颜色(透明度) */
  background: #ffffff;
  box-shadow: 0px 0px 8px 0px rgba(0, 20, 57, 0.1);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  position: relative;
  cursor: default;

  .icon-remove {
    position: absolute;
    right: 10px;
    top: 10px;
    cursor: pointer;
  }
}

.sel-city {
  display: flex;
  align-items: center;
  margin-top: 15px;
  padding: 0 10px;

  span:first-child {
    color: aqua;
    width: 100px;
  }
}

.notice {
  display: block;
  padding: 15px 5px;
}

.agree-check {
  padding: 0 5px;
}

.node-item {
  width: 100%;
  position: relative;
  box-sizing: border-box;

  .operate-btn {
    margin-left: 10px;
  }
}

.push-form {
  padding: 0 10px;

  :deep(.units) {
    width: 100% !important;

    .el-cascader-menu__wrap.el-scrollbar__wrap {
      height: 300px !important;
    }
  }
}

.form-item {
  width: 45%;
}
</style>
